﻿/**
//  Common.cs
//  Marquee Moment
//  Copyright 2011 Systematix Technocrates. All rights reserved.
**/

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using NLog;
using System.Drawing.Imaging;
using System.ComponentModel;


namespace MarqueeMoment.Entities
{
    /// <summary>
    /// Class for showing Error messages,Warnings,Asking etc.
    /// </summary>
    public static class Dialogs
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        #region Static methods

        public static DialogResult SaveChanges()
        {
            return MessageBox.Show("Changes Have Been Made SaveChanges",
                                    "Marquee Moment", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
        }

        public static DialogResult SavedSuccesfully()
        {
            return MessageBox.Show("Saved Succesfully",
                                    "Marquee Moment", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static DialogResult EmptyField()
        {
            return MessageBox.Show("Field Cannot Be Empty", "Marquee Moment", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static DialogResult DeleteObject(String message)
        {
            return MessageBox.Show(message, "Marquee Moment", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        }

        public static DialogResult InvalidValue()
        {
            return MessageBox.Show("Invalid Value", "Marquee Moment");
        }

        public static DialogResult NegativeValue()
        {
            return MessageBox.Show("Value Cannot Be Negative", "Marquee Moment");
        }

        public static DialogResult Ask(String question)
        {
            return MessageBox.Show(question, "Marquee Moment", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
        }

        public static DialogResult Question(String question)
        {
            return MessageBox.Show(question, "Marquee Moment", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        }

        public static DialogResult Error(String error)
        {
            return MessageBox.Show(error, "Marquee Moment", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static DialogResult Warning(String error)
        {
            return MessageBox.Show(error, "Marquee Moment", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public static DialogResult Exclamation(String exclamation)
        {
            return MessageBox.Show(exclamation, "Marquee Moment", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        public static DialogResult Information(String information)
        {
            return MessageBox.Show(information, "Marquee Moment", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static DialogResult AlreadyExist()
        {
            return MessageBox.Show("Record Already Exist",
                                     "Marquee Moment", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion Static methods
    }
    /// <summary>
    /// for Encryption and Decryption the Password of User
    /// </summary>
    public static class PasswordEncodeDecode
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public static string Base64Encode(string sData)
        {
            try
            {
                byte[] encData_byte = new byte[sData.Length];

                encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);

                string encodedData = Convert.ToBase64String(encData_byte);

                return encodedData;

            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error In Base64Encode" + exc.StackTrace);
            }
            return null;
        }

        public static string Base64Decode(string sData)
        {

            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();

            System.Text.Decoder utf8Decode = encoder.GetDecoder();

            byte[] todecode_byte = Convert.FromBase64String(sData);

            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

            char[] decoded_char = new char[charCount];

            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

            string result = new String(decoded_char);

            return result;

        }
    }

    public static class Common
    {
        public static Int32 imageIndex;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public static String temporaryPhotosDirPath = System.Windows.Forms.Application.StartupPath + @"\Temp\Photos\";
        public static String uploadPhotoDirectoryPath = Properties.Settings.Default.UploadPhotoDirectoryPath;
        public static String capturedPhotoDirPath = System.Windows.Forms.Application.StartupPath + @"\Temp\Photos\CapturedPhoto\";
        public static String selectedPhotoDirPath = System.Windows.Forms.Application.StartupPath + @"\Temp\Photos\SelectedPhoto\";
        public static String composedPhotoDirPath = System.Windows.Forms.Application.StartupPath + @"\Temp\Photos\ComposedPhoto\";
        public static String spinnerImagePath = System.Windows.Forms.Application.StartupPath + @"\Resources\spinner.gif";
        public static String spinnerBigImagePath = System.Windows.Forms.Application.StartupPath + @"\Resources\spinner_big.gif";
        public static String composeBGImageListDirPath = System.Windows.Forms.Application.StartupPath + @"\Resources\Background_Images\";
        public static String bottomImagePath = System.Windows.Forms.Application.StartupPath + @"\Resources\botomlogo.JPG";
        public static String listTempPhotoDirPath = System.Windows.Forms.Application.StartupPath + @"\Temp\Photos\TempPhoto\";

        public static String selectedPhotoPath()
        {
            return System.Windows.Forms.Application.StartupPath + @"\Temp\Photos\SelectedPhoto\Photo" + imageIndex + "1.jpg";
        }

        public static String composedPhotoPath()
        {
            return System.Windows.Forms.Application.StartupPath + @"\Temp\Photos\ComposedPhoto\Photo" + imageIndex + "1.jpg";
        }

        public static void SaveUpdatedSizePhoto(String imageFilePath, bool incrementIndex)
        {
            try
            {
                if (!Directory.Exists(Common.capturedPhotoDirPath))
                    Directory.CreateDirectory(Common.capturedPhotoDirPath);

                if (!Directory.Exists(Common.selectedPhotoDirPath))
                    Directory.CreateDirectory(Common.selectedPhotoDirPath);

                Bitmap tempImage = new Bitmap(imageFilePath);
                Bitmap img = new Bitmap(tempImage);
                tempImage.Dispose();

                Image importImage = (Image)img;

                int imageWidth = importImage.Width;
                int imageHeight = importImage.Height;
                if (imageWidth > 408)
                {
                    importImage.Dispose();
                    importImage = ResizeImage(imageFilePath, 408, imageHeight, true);
                    if (importImage == null)
                    {
                        logger.Error("Error in SaveUpdatedSizePhoto(String imageFilePath, bool incrementIndex)");
                        return;
                    }
                }
                Bitmap newimg = new Bitmap(importImage);
                Int32 yPOS = importImage.Height / 2 - 88;
                if (yPOS < 0)
                    yPOS = 0;

                Int32 newHeight = 176;
                if (importImage.Height < newHeight)
                    newHeight = importImage.Height;

                newimg = CropBitmap(newimg, 0, yPOS, importImage.Width, newHeight);
                if (newimg == null)
                {
                    logger.Error("Error in CropBitmap(newimg, 0, yPOS, importImage.Width, newHeight)");
                    return;
                }

                importImage = (Image)newimg;
                String photoName = GetImportPhotoName(incrementIndex);
                if (photoName == null)
                {
                    logger.Error("Error in SaveUpdatedSizePhoto(String imageFilePath, bool incrementIndex)");
                    return;
                }
                //Added below condition because we dont want to change image when it is in used
                if (!File.Exists(Common.capturedPhotoDirPath + @"\" + photoName))
                    importImage.Save(Common.capturedPhotoDirPath + @"\" + photoName, ImageFormat.Png);


                importImage.Save(Common.selectedPhotoDirPath + @"\" + photoName, ImageFormat.Png);

                importImage.Dispose();
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error in saving updated size photo");

            }
        }

        public static void UpdatePhotoSize(String imageFilePath, String savedImageFilePath)
        {
            try
            {
                if (File.Exists(imageFilePath))
                {
                    Bitmap tempImage = new Bitmap(imageFilePath);
                    Bitmap img = new Bitmap(tempImage);
                    tempImage.Dispose();

                    Image importImage = (Image)img;

                    int imageWidth = importImage.Width;
                    int imageHeight = importImage.Height;
                    if (imageWidth > 408)
                    {
                        importImage.Dispose();
                        importImage = ResizeImage(imageFilePath, 408, imageHeight, true);
                        if (importImage == null)
                        {
                            logger.Error("Error in UpdatePhotoSize(String imageFilePath, String savedImageFilePath)");
                            return;
                        }
                    }

                    importImage.Save(savedImageFilePath, ImageFormat.Png);
                    importImage.Dispose();
                    importImage = null;
                }
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error in saving updated size photo");

            }
        }

        public static DialogResult importPhoto()
        {
            try
            {
                FileDialog importImageDialog = new OpenFileDialog();
                importImageDialog.Title = "Upload Photo";

                importImageDialog.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";

                if (importImageDialog.ShowDialog() == DialogResult.OK)
                {
                    SaveUpdatedSizePhoto(importImageDialog.FileName, true);
                    return DialogResult.OK;
                }
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("The process cannot access the file because it is being used by another process.");
            }
            return DialogResult.Cancel;

        }

        public static Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
        {
            try
            {
                Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
                Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
                return cropped;
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error in croping image");
            }
            return null;
        }

        private static Image ResizeImage(string OriginalFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            try
            {
                Bitmap tempImage = new Bitmap(OriginalFile);
                Bitmap img = new Bitmap(tempImage);
                tempImage.Dispose();

                Image FullsizeImage = (Image)img;

                /*
                // Prevent using images internal thumbnail
                FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                */

                if (OnlyResizeIfWider)
                {
                    if (FullsizeImage.Width <= NewWidth)
                    {
                        NewWidth = FullsizeImage.Width;
                    }
                }

                int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
                Bitmap b = new Bitmap(NewWidth, NewHeight);
                Graphics g = Graphics.FromImage((Image)b);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(FullsizeImage, 0, 0, NewWidth, NewHeight);
                g.Dispose();
                FullsizeImage.Dispose();
                return (Image)b;
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error in image resizing");
            }
            return null;
        }

        public static String GetImportPhotoName(bool incrementIndex)
        {
            try
            {
                String photoName = string.Empty;
                if (incrementIndex)
                    imageIndex++;

                photoName = "Photo" + imageIndex + "1.Jpg";

                return photoName;
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error in geting Import Photo Name");
            }
            return null;
        }

        public static void clearTempPhotosDir()
        {
            try
            {
                if (Directory.Exists(temporaryPhotosDirPath))
                    Directory.Delete(temporaryPhotosDirPath, true);
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
            }
        }

        /// <summary>
        /// get path at user directory
        /// </summary>
        public static String GetUserDirLOC(String imageName)
        {
            try
            {
                if (!Directory.Exists(Common.uploadPhotoDirectoryPath))
                {
                   // System.ComponentModel.BackgroundWorker bgWorker = new System.ComponentModel.BackgroundWorker();
                    Dialogs.Exclamation("Invalid Upload Directory Path, add proper path in XML Configuration File for key: UploadPhotoDirectoryPath.\n \nYou Message has been Archived.");
                  //  bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork_addToArchive);
                   // bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_Completed_addToArchive);
                  //  bgWorker.RunWorkerAsync();
                   // MarqueeMoment.Forms.frmScheduleScreen.
                    return null;
                }
                return Common.uploadPhotoDirectoryPath + @imageName;

            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error on Get Network Directory LOC");

            }
            return null;
        }

        /// <summary>
        /// Delete image from Network place
        /// </summary>
        /// <param name="schedule"></param>
        public static void DeleteFromNetworkResource(ScheduleEntity schedule)
        {
            String ImageFile = "MM_" + schedule.ScheduleTime.ToString("MM-dd-yyyy_hh_mm_ss") + ".jpg";
            String networkImagePath = Common.GetUserDirLOC(ImageFile);
            if (networkImagePath != null)
            {
                try
                {
                    if (File.Exists(networkImagePath))
                        File.Delete(networkImagePath);
                }
                catch (Exception exc)
                {
                    logger.Error(exc.StackTrace);
                    Dialogs.Error("File named " + ImageFile + " is in used");
                }
            }

        }

        /// <summary>
        /// To get image path corresponding  to the grid row index
        /// </summary>
        /// <param name="rowIndex">grid row index</param>
        /// <returns>image path </returns>
        public static String GetImagePath(Int32 rowIndex)
        {
            String fileName = "Photo" + imageIndex;
            String imagePath = capturedPhotoDirPath + fileName + (rowIndex + 1) + ".Jpg";
            return imagePath;
        }
    }
}
